import os

from flask import render_template, send_from_directory, request, session, abort, send_file
from app.controller import Api

import subprocess
from app.utils import Shell

list = {}
id_list = {}

def execute_command(command,ws):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, text=True)
    for line in iter(process.stdout.readline, ''):
        print(line, end='')
        ws.emit("response", {"value": line}, namespace="/Shell")

    process.stdout.close()
    return_code = process.wait()




def get_route(app, cfg, ROOT_PATH, ws):
    @app.before_request
    def before_request_func():
        if cfg["safe_entry"] not in str(request.path):

            if "username" in session and "pw" in session:
                if cfg[session.get('username')] != session.get('pw'):
                    print(1)
                    if cfg["safe_entry"] not in str(request.referrer):
                        abort(404)
            else:
                if cfg["safe_entry"] not in str(request.referrer):
                    print(str(request.referrer))
                    abort(404)

    @app.errorhandler(404)
    def page_error(e):
        return render_template('error.html'), 404

    @app.route("/")
    @app.route("/home")
    @app.route("/site")
    @app.route("/db")
    @app.route("/set")
    @app.route("/safe")
    @app.route("/shell")
    @app.route("/soft")
    @app.route("/set")
    @app.route("/file")
    @app.route("/safe/port")
    def home():
        return send_from_directory(os.getcwd() + "/vue/dist", "index.html")

    @app.route("/p/<path:path>")
    def page(path):
        return render_template("/p/" + path + '.html')

    @app.route("/" + cfg["safe_entry"])
    def login():
        return render_template('login.html')

    @app.route('/static/<path:path>')
    def static_file(path):
        # 使用send_from_directory函数来发送静态文件
        return send_from_directory(app.static_folder, path)

    @app.route('/assets/<path:path>')
    def assets_file(path):
        # 使用send_from_directory函数来发送静态文件
        return send_from_directory(os.getcwd() + "/vue/dist/assets", path)

    @app.route('/favicon.ico')
    def favicon():
        # 使用send_from_directory函数来发送静态文件
        return send_file(ROOT_PATH + '/public/favicon.ico', mimetype='image/vnd.microsoft.icon')

    @app.route('/api/<path:path>', methods=['POST', 'GET'])
    def api_controller(path):
        return Api.service(path, cfg, request.data, request)

    # 出现消息后,率先执行此处
    @ws.on("message", namespace="/Shell")
    def socket(message):
        global list
        if cfg["safe_entry"] not in str(request.path):

            if "username" in session and "pw" in session:
                if cfg[session.get('username')] != session.get('pw'):
                    print(1)
                    if cfg["safe_entry"] not in str(request.referrer):
                        ws.emit("response", {"value": "wrong"}, namespace="/Shell")

            else:
                if cfg["safe_entry"] not in str(request.referrer):
                    print(str(request.referrer))
                    ws.emit("response", {"value": "wrong"}, namespace="/Shell")

        print("接收到消息:", message['command'])

        command = message['command']
        id = message['id']
        if len(command) != 0:
            splite_command = command.split(" ")

            if splite_command[0] == "help":
                ws.emit("response", {"value": "version 1.0 \n"}, namespace="/Shell")

            elif splite_command[0] == "Ping":
                if len(splite_command) == 2:
                    index = splite_command[1]
                    for each in range(int(index)):
                        ws.sleep(0.1)
                        ws.emit("response", {"value": str(each) + "\n"}, namespace="/Shell")
                    ws.emit("response", {"value": "\n[shell] # "}, namespace="/Shell")
            else:

                list = Shell.Shell(command, ws, id, list=list)
                print(list)
        else:
            list= Shell.Shell(command, ws, id, list=list)
            print(list)

    # 当websocket连接成功时,自动触发connect默认方法
    @ws.on("connect", namespace="/Shell")
    def connect():
        if cfg["safe_entry"] not in str(request.path):

            if "username" in session and "pw" in session:
                if cfg[session.get('username')] != session.get('pw'):
                    print(1)
                    if cfg["safe_entry"] not in str(request.referrer):
                        print("无权限")
            else:
                if cfg["safe_entry"] not in str(request.referrer):
                    print(str(request.referrer))
                    print("无权限")
        print("链接建立成功..")



